#include<iostream>
#include<signal.h>
#include <unistd.h>
#include<vector>

sigset_t signset;
void PrintPending(sigset_t &pending){
    std::cout << "curr process[" << getpid() << "]pending: ";
    for (int signo = 31; signo >= 1; signo--){
        if (sigismember(&pending, signo)){
            std::cout << 1;
        }
        else{
            std::cout << 0;
        }
    }
    std::cout << "\n";
}
//获取信号集中信号的状态
void get_signal(std::vector<int>& signals,sigset_t& sig){
    for(int i=1;i<32;i++){
        if(sigismember(&sig, i)){
            signals[i]=1;
        }
    }
}
void handler1(int a){//验证是先调用处理方法还是先设置信号集
    std::cout << "Received signal: " << a << std::endl;
    PrintPending(signset);
    exit(0);
}
void handler2(int a){
    std::cout << "Received signal: " << a << std::endl;
    //取消对SIGINT的屏蔽
    int n=sigdelset(&signset, SIGINT);
    if(n==-1){
        perror("sigdelset:");
        return;
    }
    n=sigprocmask(SIG_SETMASK, &signset, NULL);
    if(n==-1){
        perror("sigprocmask:");
        return;
    }
}

int main(){
    signal(SIGINT, handler1);
    signal(SIGALRM, handler2);
    int n=sigemptyset(&signset);
    if(n==-1){
        perror("sigemptyset:");
        return 1;
    }
    //屏蔽SIGINT
    n=sigaddset(&signset, SIGINT);
    if(n==-1){  
        perror("sigaddset:");
        return 1;
    }
    n=sigprocmask(SIG_SETMASK, &signset, NULL);
    PrintPending(signset);
    //给自己发送SIGINT信号
    raise(SIGINT);
    // std::vector<int> t(32);
    // get_signal(t,signset);
    // for(int i=1;i<32;i++){
    //     if(t[i]){
    //         std::cout<<t[i];
    //     }
    // }
    // std::cout<<std::endl;
    if(n==-1){
        perror("sigprocmask:");
        return 1;
    }
    alarm(5);
    sigset_t sig;
    sigemptyset(&sig);
    std::vector<int> signals(32);
    while(true){
        std::cout<<"Waiting for signal"<<std::endl;
        int n=sigpending(&sig);
        if(n==-1){
            perror("sigpending:");
            return 1;
        }
        std::cout<<"Pending signals: ";
        get_signal(signals,sig);
        for(int i=1;i<32;i++){
            std::cout<<signals[i];
            signals[i]=0;
        }
        std::cout<<std::endl;
        sleep(1);
    }
    return 0;
}